package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutContract;
import com.lkd.contract.VendoutData;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author ChenChangYu
 * @Date 2022 09 23 10 21
 **/
@Component
@Slf4j
@Topic(TopicConfig.VMS_VENDOUT_TOPIC)
public class VendoutHandler implements MsgHandler {

    @Autowired
    private VendoutRunningService vendoutRunningService;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 接收订单微服务返回的信息
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        if (StringUtils.isBlank(jsonMsg)){
            throw new LogicException("接收消息失败");
        }

        VendoutContract vendoutContract = JsonUtil.getByJson(jsonMsg, VendoutContract.class);
        if (vendoutContract == null){
            return;
        }
        //保存出货流水
        vendoutRunningService.vendout(vendoutContract);

        //扣减库存和流水后释放锁
        RLock lock = redissonClient.getLock(String.format(VMSystem.ORDER_LOCK_KEY, vendoutContract.getInnerCode()));
        lock.unlock();
    }
}

































